package com.hw8.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ehw8.base.domain.pojo.Result;
import com.google.gson.Gson;
import com.hw8.CosConstants;
import com.hw8.CosService;
import com.hw8.mongo.MongoUtils;
import com.hw8.mongoDao.CommentMongoDao;
import com.hw8.mongoDao.GoodsMongoDao;
import com.hw8.mongoDao.SupportMongoDao;
import com.hw8.mongobean.*;
import com.hw8.utils.ErrorEnum;
import com.mongodb.client.result.DeleteResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static com.hw8.mongo.MongoUtils.getNextId;

@Api("朋友圈操作")
@RestController
@RequestMapping("moments")
@Slf4j
public class OperationController {

    @Resource
    private HttpServletRequest request;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private SupportMongoDao supportMongoDao;
    @Resource
    private GoodsMongoDao goodsMongoDao;
    @Resource
    private CommentMongoDao commentMongoDao;
    @Resource
    private CosService cosService;

    @ApiOperation("发布朋友圈")
    @PostMapping("/content/add")
    public Result contentAdd(@RequestBody Map map){
        Gson gson = new Gson();
        Object goodsObj = map.get("goods");
        Goods goods = null;
        if(goodsObj != null && ((Map)goodsObj).size() > 0){
            goods = JSON.parseObject(gson.toJson(goodsObj), Goods.class);
        }
        Share share = JSON.parseObject(gson.toJson(map), Share.class);
        Long userId = getUserId();
        if(share.getUid() == null){
            share.setUid(userId);
        }

        Long nextId = getNextId(Share.class.getSimpleName());
        share.setCid(nextId);
        share.setSupports(0);
        share.setComments(0);
        share.setCreateTime(new Date());
        if(goods != null){
            if(goods.getGid() == null){
                return ErrorEnum.PARAMETER_ERROR.getResult();
            }
            Goods srcObj = new Goods();
            srcObj.setGid(goods.getGid());
            goodsMongoDao.updateInsert(srcObj,goods);
            share.setGoodsId(goods.getGid());
        }
        mongoTemplate.insert(share);
        return Result.success(1);
    }

    @ApiOperation("删除自己的朋友圈内容")
    @PostMapping("/content/del")
    public Result contentDel(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        Long contentId = jsonObject.getLong("contentId");
        long num = mongoTemplate.count(new Query(Criteria.where("cid").is(contentId).and("uid").is(userId)),Share.class);
        if(num == 0){
            String format = String.format("user={},删除content={}失败", userId, contentId);
            log.error(format);
            return Result.fail("删除失败");
        }
        Query query = new Query(Criteria.where("cid").is(contentId));
        mongoTemplate.remove(query,Share.class);
        return Result.success("");
    }

    @ApiOperation("上传图片")
    @PostMapping("/image/upload")
    public Result imageUpload(@RequestPart(value="image", required = false) MultipartFile file){
        if(file == null) {
            return Result.fail( "上传文件不能为空");
        }
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            log.error("===step1.1:【上传图片接口-获取byte数组异常, Exception = {}", e.getMessage());
        }
        String originalFilename = file.getOriginalFilename();

        String url = cosService.upload(bytes, originalFilename, CosConstants.FILE_TYPE_MOMENT);
//    	log.info("===step2:【上传图片接口】(UploadController-uploadImage)-返回信息, result:{}", result);
        return Result.success(url);
    }


    @ApiOperation("点赞")
    @PostMapping("/content/like")
    public Result contentLike(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        Long contentId = jsonObject.getLong("contentId");

        Support support = new Support();
        support.setUid(userId);
        support.setContentId(contentId);
        Long count = supportMongoDao.getCount(support);
        if(count > 0){
            return Result.success("");
        }

        Update update = new Update();
        update.inc("supports", 1);
        mongoTemplate.updateFirst(new Query(Criteria.where("cid").is(contentId)),update,Share.class);

        support.setSid(MongoUtils.getNextId(Support.class));
        support.setCreateTime(new Date());
        mongoTemplate.save(support);
        return Result.success("");
    }

    @ApiOperation("取消点赞")
    @PostMapping("/content/unlike")
    public Result contentUnlike(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        Long contentId = jsonObject.getLong("contentId");

        Query query = new Query(Criteria.where("uid").is(userId).and("contentId").is(contentId));
        DeleteResult result = mongoTemplate.remove(query, Support.class);
        if(result.getDeletedCount() > 0){
            Update update = new Update();
            update.inc("supports", -1);
            mongoTemplate.updateFirst(new Query(Criteria.where("cid").is(contentId)),update,Share.class);
        }

        return Result.success("");
    }


    @ApiOperation("发布评论")
    @PostMapping("/content/comment/add")
    public Result commentAdd(@RequestBody Comment comment){
        Update update = new Update();
        update.inc("comments", 1);
        mongoTemplate.updateFirst(new Query(Criteria.where("cid").is(comment.getContentId())),update,Share.class);

        Long userId = getUserId();
        Long nextId = getNextId(Comment.class.getSimpleName());
        comment.setCid(nextId.intValue());
        comment.setUid(userId);
        comment.setCreateTime(new Date());
        mongoTemplate.insert(comment);
        return Result.success("");
    }


    @ApiOperation("删除评论")
    @PostMapping("/content/comment/del")
    public Result commentDel(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        Integer commentId = jsonObject.getInteger("commentId");
        Comment comment = new Comment();
        comment.setCid(commentId);
        Comment result = commentMongoDao.queryOne(comment);
        if(result == null || !result.getUid().equals(userId)){
            String format = String.format("user={},删除comment={}失败", userId, commentId);
            log.error(format);
            return Result.fail("删除失败");
        }
        Query query = new Query(Criteria.where("cid").is(commentId));
        DeleteResult remove = mongoTemplate.remove(query, Comment.class);
        if(remove.getDeletedCount() > 0) {
            Update update = new Update();
            update.inc("comments", -1);
            mongoTemplate.updateFirst(new Query(Criteria.where("cid").is(result.getContentId())), update, Share.class);
        }
        return Result.success("");
    }

    @ApiOperation("关注用户")
    @PostMapping("/user/follow")
    public Result followUser(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        Long personId = jsonObject.getLong("personId");

        if(personId == null){
            return ErrorEnum.PARAMETER_ERROR.getResult();
        }

        Update update = new Update();
        update.push("favoriteUids",personId);
        mongoTemplate.updateFirst(new Query(Criteria.where("uid").is(userId)),update, Favorite.class);
        return Result.success("");
    }

    @ApiOperation("取消关注用户")
    @PostMapping("/user/unfollow")
    public Result unfollowUser(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        Long personId = jsonObject.getLong("personId");

        if(personId == null){
            return ErrorEnum.PARAMETER_ERROR.getResult();
        }

        Update update = new Update();
        update.pull("favoriteUids",personId);
        mongoTemplate.updateFirst(new Query(Criteria.where("uid").is(userId)),update, Favorite.class);
        return Result.success("");
    }

    @ApiOperation("更改个人主页背景")
    @PostMapping("/mine/bgPic")
    public Result updateBgPic(@RequestBody JSONObject jsonObject){
        Long userId = getUserId();
        String bgPic = jsonObject.getString("bgPic");

        if(StringUtils.isBlank(bgPic)){
            return ErrorEnum.PARAMETER_ERROR.getResult();
        }

        Update update = new Update();
        update.set("bgPic",bgPic);
        mongoTemplate.updateFirst(new Query(Criteria.where("uid").is(userId)),update, User.class);
        return Result.success("");
    }

    @ApiOperation("投诉")
    @PostMapping("/complaint/add")
    public Result complaintAdd(@RequestBody Complaint complaint){
        Long userId = getUserId();
        Long nextId = getNextId(Complaint.class.getSimpleName());
        complaint.setCid(nextId.intValue());
        complaint.setUid(userId.intValue());
        mongoTemplate.insert(complaint);
        return Result.success("");
    }


    private Long getUserId() {
        return (Long) request.getAttribute("userId");
    }
}
